#!/bin/sh
#
# Perform necessary datadog-dogstatsd setup steps before package is installed.
#
# .deb: STEP 2 of 5
# .rpm: STEP 2 of 6

INSTALL_DIR=/opt/datadog-dogstatsd
SERVICE_NAME=datadog-dogstatsd

KNOWN_DISTRIBUTION="(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|Arista|SUSE)"
DISTRIBUTION=$(lsb_release -d 2>/dev/null | grep -Eo $KNOWN_DISTRIBUTION  || grep -Eo $KNOWN_DISTRIBUTION /etc/issue 2>/dev/null || grep -Eo $KNOWN_DISTRIBUTION /etc/Eos-release 2>/dev/null || grep -m1 -Eo $KNOWN_DISTRIBUTION /etc/os-release 2>/dev/null || uname -s)

if [ "$DISTRIBUTION" = "Darwin" ]; then
    echo "Dogstatsd is not supported on MacOS"
    exit 0
fi

# Linux installation
set -e
if [ -f "/lib/systemd/system/$SERVICE_NAME.service" ] || [ -f "/usr/lib/systemd/system/$SERVICE_NAME.service" ]; then
    # Stop an already running agent
    # Only supports systemd and upstart
    if command -v systemctl >/dev/null 2>&1; then
        systemctl stop $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl stop $SERVICE_NAME || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-dogstatsd package only provides service files for systemd and upstart."
    fi
fi

if [ -f "/etc/debian_version" ] || [ "$DISTRIBUTION" = "Debian" ] || [ "$DISTRIBUTION" = "Ubuntu" ]; then
    # Nothing specific on Debian
    :
    #DEBHELPER#
elif [ -f "/etc/redhat-release" ] || [ -f "/etc/system-release" ] || [ -f "/etc/SuSE-release" ] || [ "$DISTRIBUTION" = "RedHat" ] || [ "$DISTRIBUTION" = "CentOS" ] || [ "$DISTRIBUTION" = "openSUSE" ] || [ "$DISTRIBUTION" = "Amazon" ] || [ "$DISTRIBUTION" = "SUSE" ] || [ "$DISTRIBUTION" = "Arista" ]; then
    # Set up `dd-agent` user and group
    getent group dd-agent >/dev/null || groupadd -r dd-agent
    getent passwd dd-agent >/dev/null || \
        useradd -r -M -g dd-agent -d $INSTALL_DIR -s /sbin/nologin \
            -c "Datadog Agent" dd-agent && \
            { usermod -L dd-agent || echo "[ WARNING ]\tCannot lock the 'dd-agent' user account"; }
else
    echo "[ FAILED ]\tYour system is currently not supported by this script.";
    exit 1;
fi

exit 0
